#import warnings
import numpy as np
import pandas as pd
import matplotlib as mpl
import matplotlib.pyplot as plt

from sklearn.model_selection import train_test_split,GridSearchCV
from sklearn.svm import SVR #对比SVC，是svm的回归形式

## 设置属性防止中文乱码
mpl.rcParams['font.sans-serif']=[u'simHei']
mpl.rcParams['axes.unicode_minus']=False

def no_empty(s):
    return s!=''

def main():
    ## 加载数据
    #names = ['CRIM','ZN', 'INDUS','CHAS','NOX','RM','AGE','DIS','RAD','TAX','PTRATIO','B','LSTAT']
    path='../data/boston_housing.data'
    ## 由于数据文件格式不统一，所以读取的时候，先按照一行一个字段属性读取数据，然后再安装每行数据进行处理
    df=pd.read_csv(path,header=None)
    data=np.empty((len(df),14))
    for i,d in enumerate(df.values):
        d=map(float,filter(no_empty,d[0].split(' ')))
        data[i]=list(d)
        
    ## 分割数据
    X,Y=np.split(data,(13,),axis=1)
    Y=Y.ravel()   # 转换格式
    print('样本数据量:%d, 特征个数：%d' %X.shape)
    print('target样本数据量:%d' %Y.shape[0])
    
    # 数据分割
    X_train,X_test,Y_train,Y_test=train_test_split(X,Y,test_size=0.2,random_state=28)
    
    ## 模型构建（参数类型和SVC基本一样）
    parameters={
        'kernel':['linear','rbf'],
        'C':[0.1,0.5,0.9,1,5],
        'gamma':[0.001,0.01,0.1,1]
    }
    model=GridSearchCV(SVR(),param_grid=parameters,cv=3)
    model.fit(X_train,Y_train)
    
    ## 获取最优参数
    print('最优参数列表:',model.best_params_)
    print('最优模型:',model.best_estimator_)
    print('最优准确率:',model.best_score_)
    
    ## 模型效果输出
    print('训练集准确率:%.2f%%'%(model.score(X_train,Y_train)*100))
    print('测试集准确率:%.2f%%'%(model.score(X_test,Y_test)*100))
    
    ## 画图
    #colors = ['g-', 'b-']
    ln_X_test=range(len(X_test))
    Y_predict=model.predict(X_test)
    
    plt.figure(figsize=(16,8),facecolor='w')
    plt.plot(ln_X_test,Y_test,'r-',lw=2,label=u'真实值')
    plt.plot(ln_X_test,Y_predict,'g-',lw=3,label=u'SVR算法估计值,$R^2$=%.3f'%(model.best_score_))
    
    # 图形显示
    plt.legend(loc='upper left')
    plt.grid(True)
    plt.title(u'波士顿房屋价格预测(SVM)')   
    plt.xlim(0,101)
    plt.show() 
    

main()